package com.example.filter;

import com.example.common.ApiRestResponse;
import com.example.common.Constant;
import com.example.exception.ImoocMallExceptionEnum;
import com.example.mall.model.pojo.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class AdminFilter implements Filter {
@Autowired
    UserService userService;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest) servletRequest;
        HttpSession session = servletRequest1.getSession();
    User currentUser = (User) session.getAttribute(Constant.Imooc_Mall_User);
//    校验是否登录
        if(currentUser==null){
            PrintWriter out =  new HttpServletResponseWrapper((HttpServletResponse)servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10007,\n" +
                    "    \"msg\": \"NO_LOGIN_USER\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            return;
        }
//        校验是否管理员
        boolean adminRole = userService.CheckLoginRole(currentUser);
        if(adminRole){
            filterChain.doFilter(servletRequest,servletResponse);
        }else{
            PrintWriter out =  new HttpServletResponseWrapper((HttpServletResponse)servletResponse).getWriter();
            out.write("{\n" +
                    "    \"status\": 10011,\n" +
                    "    \"msg\": \"No_MAGGER_ROLE\",\n" +
                    "    \"data\": null\n" +
                    "}");
            out.flush();
            out.close();
        }
    }

    @Override
    public void destroy() {

    }
}
